<template>
  <!-- 城市选择页面 -->
  <div class="city-picker c-pv16">
    <img class="c-pa c-p-t0 c-w100 c-maxw640 c-pz-1 c-hh268" src="../../../assets/i/bg-blue.png" alt="">
    <div class="c-justify-center c-flex-row c-aligni-center c-ph30 c-pt12 c-pb30 c-w100 c-maxw640 c-pz99 c-p">
      <div class="c-flex-row c-aligni-center c-fc-white c-mr20">
        <i class="iconfont c-fs22 c-mr10">&#xe8fe;</i>
        <div class="c-fs28 c-mr10">{{locateCity}}</div>
      </div>
      <div class="c-fc-white c-br30 c-fs24 c-bg-sgray c-hh60 c-flex-row c-flex-grow1 c-w0 c-aligni-center c-ph24 booking-search">
        <span class="iconfont c-fs24">&#xe6d6;</span>
        <form action="javascript:return true;">
          <input id="searchValue" ref="input" @focus="inputFocus" @blur="inputBlur" class="c-w100 c-fc-white" v-model="searchValue" name="searchValue" placeholder="输入详细地址" type="search">
        </form>
      </div>
    </div>
    <div class="c-flex-row c-pz99 list-tab c-fc-white c-aligni-center c-justify-sb c-ph24 c-mb30">
      <div class="c-fs28 c-w0 c-flex-grow1 c-text-ellipsis1">{{detailPosition}}</div>
      <div @click="getLocation(1)" class="c-flex-row c-aligni-center c-ml20">
        <span class="iconfont c-fs30 c-mr10">&#xe905;</span>
        <span class="c-fs24">重新定位</span>
      </div>
    </div>
    <!-- 城市列表 -->
    <div class="c-bg-white c-br-tl24 c-br-tr24 c-w100 c-maxw640 c-pz98 c-pb30 city-wrapper-hook c-pa c-p-b0 c-p-t230 c-text-hidden" v-if="cities.length > 0">
      <city-list :cities="cities" :letter="letter" :showCity="showCity" @chooseCity="chooseCity" @change="handleLetterChange"></city-list>
      <city-alphabet :cities="cities" :letter="letter" :showCity="showCity" @change="handleLetterChange"></city-alphabet>
    </div>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js"
import { loadBMap } from "@/utils/loadBMap.js"
import cityList from "./cityList.vue";
import cityAlphabet from "./cityAlphabet.vue";
let inputScrollTop = 0;
export default {
  name: "CityPicker",
  components: {
    cityList,
    cityAlphabet
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      themeName: localStorage.getItem("themeName") ? localStorage.getItem("themeName") : "mb5",
      isLoading: false,
      searchValue: '',
      isFocus: false,
      locateCity: '未知',
      cities: [],
      scroll: null,
      detailPosition: '',
      submit: {
        sms_captcha: '',
        captcha: '',
        area_code: '',
        _token: '',
      },
      cityLon: null, //所选城市经度
      cityLa: null, //所选城市纬度
      userlocation: '',
      lng: '',
      letter: 'A',
      ac: '',
      showCity: true
    }
  },
  watch: {
    locateCity() {
      this.$refs.input.blur();
      this.$refs.input.focus();
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
  },
  activated() {
    this.isLoading = false;
    this.searchValue = '';
    this.isFocus = false;
    this.detailPosition = this.$route.query.locateAddress || '';
    this.locateCity = this.$route.query.locateCity || '未知';
    this.companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
    this.cityLon = null; //
    this.cityLa = null;
    this.userlocation = '';
    this.letter = 'A';
    this.showCity = true;
    this.ac = '';
    if (this.locateCity != '未知') {
      this.$refs.input.focus();
    }
    setDocumentTitle("预约");
    utilJs.getMethod(`${global.apiurl}common/areaList`, res => {
      this.cities = res;
      this.$nextTick(() => {
        loadBMap().then(BMap => {
          if (this.locateAddress == '未知') {
            this.getLocation();
          } else {
            this.queryAddress();
          }
        })
      })
    }, fres => {});
    // utilJs.syncLoadJs("https://webapi.amap.com/maps?v=1.4.15&key=f051a3d0ab2acef596ce8dbd7fe3a629");
    // if (this.detailPosition == '') {
    //   this.getLocation();
    // } else {
    //   this.queryAddress();
    // }
    this.wechatShare();
  },
  methods: {
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      this.showCity = true;
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    chooseCity(city) {
      this.locateCity = city;
      this.ac.dispose();
      this.queryAddress();
    },
    handleLetterChange(letter) {
      this.letter = letter
    },
    // 百度搜索地址
    queryAddress() {
      /* eslint-disable */
      let that = this;
      let ac = new BMap.Autocomplete( // 建立一个自动完成的对象
        {
          'input': 'searchValue',
          'location': this.locateCity,
        })
      that.ac = ac;
      var myValue;
      ac.addEventListener('onconfirm', function (e) { // 鼠标点击下拉列表后的事件
        that.$refs.input.blur();
        let _value = e.item.value //获取点击的条目
        if (_value.city == _value.district) {
          that.detailPosition = myValue = _value.city
        } else {
          that.detailPosition = myValue = _value.city + _value.district + _value.street + _value.business
        }
        //地址拼接赋给详细地址
        that.locateCity = _value.city;
        let myGeo = new BMap.Geocoder();
        myGeo.getPoint(myValue, function (point) {
          ac.dispose();
          // if (point) {
          //   that.$routerGo(that, "replace", { path: `/homePage/booking/bookingList?detailPosition=${that.detailPosition}&lng=${point.lng}&lat=${point.lat}&locateCity=${that.locateCity}` });
          // }
        },
          this.locateCity);
        setPlace()
      })
      function setPlace() {
        var local = new BMap.LocalSearch(that.locateCity, { // 在当前城市智能搜索
          onSearchComplete: myFun,
        })
        function myFun() {
          let userlocation = local.getResults().getPoi(0).point // 获取第一个智能搜索的结果
          setTimeout(function () {
            that.$routerGo(that, "replace", { path: `/homePage/booking/bookingList?detailPosition=${that.detailPosition}&lng=${userlocation.lng}&lat=${userlocation.lat}&locateCity=${that.locateCity}&inputScrollTop=${inputScrollTop}` });
          }, 100);
        }
        local.search(myValue)
      }
      /* eslint-disable */
    },
    // 高德搜索地址
    // queryAddress() {
    //   /* eslint-disable */
    //   let that = this;
    //   AMap.plugin('AMap.Autocomplete', function(){
    //   // 实例化Autocomplete
    //   var autoOptions = {
    //     // input 为绑定输入提示功能的input的DOM ID
    //     input: 'searchValue',
    //     city: that.locateCity,
    //     citylimit: true,
    //     datatype: 'poi',
    //     output: 'resultList'
    //   };
    //   var autoComplete= new AMap.Autocomplete(autoOptions);
    //   // this.ac = autoComplete;
    //   AMap.event.addListener(autoComplete, "select", function(e){
    //     that.detailPosition = e.poi.name; //地址拼接赋给详细地址
    //     let lng = e.poi.location.lng;
    //     let lat = e.poi.location.lat;
    //     setTimeout(function () {
    //       that.$routerGo(that, "replace", { path: `/homePage/booking/bookingList?detailPosition=${that.detailPosition}&lng=${lng}&lat=${lat}&locateCity=${that.locateCity}&inputScrollTop=${inputScrollTop}` });
    //     }, 500);
    //   })
    // })
    // },
    //百度获取地理位置
    getLocation(type) {
      /* eslint-disable */
      let that = this;
      let geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
          that.lng = r.point.lng;
          that.lat = r.point.lat;
          let gc = new BMap.Geocoder();
          gc.getLocation(r.point, function (rs) {
            const addComp = rs.addressComponents;
            // 可以通过addComp对象获取到省、市、县、区、街道多少号等信息
            that.locateCity = addComp.city;
            that.detailPosition = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
            if (type == 1) {
              that.$routerGo(that, "replace", { path: `/homePage/booking/bookingList?detailPosition=${that.detailPosition}&lng=${that.lng}&lat=${that.lat}&locateCity=${that.locateCity}` });
            } else {
              that.queryAddress();
            }
          })
        }
        else {
          that.getTags();
        }        
      });
    },
    // 高德定位
    // getLocation(type) {
    //   let that = this;
    //   // that.$loading.show({
    //   //   text: "定位中"
    //   // });
    //   /* eslint-disable */
    //   AMap.plugin('AMap.Geolocation', function() {
    //     var geolocation = new AMap.Geolocation({
    //       // 是否使用高精度定位，默认：true
    //       enableHighAccuracy: true,
    //       // 设置定位超时时间，默认：无穷大
    //       timeout: 10000,
    //     })

    //     geolocation.getCurrentPosition()
    //     AMap.event.addListener(geolocation, 'complete', onComplete)
    //     AMap.event.addListener(geolocation, 'error', onError)

    //     function onComplete (data) {
    //       // data是具体的定位信息
    //       let addComp = data.addressComponent;
    //       that.locateCity = addComp.city;
    //       that.detailPosition = addComp.city + addComp.district + addComp.township + addComp.street + addComp.streetNumber;
    //       that.lng = data.position.split(',')[0];
    //       that.lat = data.position.split(',')[1];
    //       if (type == 1) {
    //       that.$routerGo(that, "replace", { path: `/homePage/booking/bookingList?detailPosition=${that.detailPosition}&lng=${that.lng}&lat=${that.lat}&locateCity=${that.locateCity}` });
    //     } else {
    //       that.queryAddress();
    //     }
    //     }

    //     function onError (data) {
    //       // 定位出错
    //       that.queryAddress();
    //     }
    //   })
      /* eslint-disable */
    // },
    //分享
    wechatShare: function () {
      let title = "预约";
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/booking/bookingList?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = window.localStorage.getItem("shareDesc");
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      let title = "预约";
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/booking/bookingList?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = window.localStorage.getItem("shareDesc");
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
  deactivated() {
    this.ac.dispose();
  },
}
</script>

<style>
.city-picker {
  background-size: 100% 130px;
}
.city-picker input {
  font-size: 0.65rem;
  padding: 0 0 0 0.4rem;
  border: 0;
  background: none;
  outline: none;
}

.city-picker input:focus {
  outline: none;
}
.city-picker input[type="search"] {
  -webkit-appearance: textfield;
  -webkit-box-sizing: content-box;
}
.city-picker input::-webkit-search-decoration,
.city-picker input::-webkit-search-cancel-button {
  display: none;
}
.city-picker .booking-search {
  background: rgba(17, 67, 155, 0.2);
}
.city-picker ::-webkit-input-placeholder {
  /* WebKit browsers */
  color: rgba(255, 255, 255, 0.7);
}
.city-picker :-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  color: rgba(255, 255, 255, 0.7);
}
.city-picker ::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: rgba(255, 255, 255, 0.7);
}
.city-picker :-ms-input-placeholder {
  /* Internet Explorer 10+ */
  color: rgba(255, 255, 255, 0.7);
}
.city-picker .booking-tag {
  background-color: #f5f6f6;
}
.city-picker .mask {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 100%;
  z-index: 100;
}
.city-picker .c-pz96 {
  z-index: 96;
}
.city-picker .c-pz97 {
  z-index: 97;
}
.city-picker .c-pz98 {
  z-index: 98;
}
.city-picker .booking-tag-selected {
  background-color: #5491ff;
}
.city-picker .selected-fc {
  color: #5491ff;
}
.city-picker .c-mr60 {
  margin-right: 1.5rem;
}
.city-picker .c-lh54 {
  line-height: 1.35rem;
}
.city-picker .c-mt30 {
  margin-top: 0.75rem;
}
.city-picker .c-hh236 {
  height: 5.9rem;
}
.city-picker .c-mh12 {
  margin-left: 0.3rem;
  margin-right: 0.3rem;
}
.city-picker .c-mh-12 {
  margin-left: -0.3rem;
  margin-right: -0.3rem;
}
.city-picker .c-hh268 {
  height: 6.7rem;
}
.city-picker .bb-ed {
  border-bottom: 1px solid #ededed;
}
.city-picker .p-t8 {
  top: 8rem;
}
.city-picker .c-p-t230 {
  top: 5.75rem;
}
.city-picker .booking-hh30 {
  height: 30px;
}
.city-picker .booking-lh40 {
  line-height: 40px;
}
.city-picker .booking-hh40 {
  height: 40px;
}
.city-picker table,
.city-picker tbody {
  border: 0;
}
</style>
